/**
 * 时间模型
 */
define(function(require, exports, module) {

    var Backbone = require('backbone'),
        _ = require('underscore'),
        moment = require('moment');
    /**
     * 时间模型：开始时间、结束时间
     */
    module.exports = Backbone.Model.extend({
        defaults: {
            startAt: 0,
            endAt: 0,
        },
        initialize: function () {
            //当前时间
            var now = parseInt(moment().format('X'));
            //如果
            if( this.get('startAt') <= 0 ) this.set('startAt', now);
            if( this.get('endAt') <= 0 ) this.set('endAt', this.get('startAt'));
        },
        validate: function(attrs, options) {
            if(attrs.startAt > attrs.endAt) return '结束时间必须在开始时间之后';
        },
        showData: function() {
            return {
                startAt: moment.unix(this.get('startAt')).format('YYYY-MM-DD HH:mm'),
                endAt: moment.unix(this.get('endAt')).format('YYYY-MM-DD HH:mm')
            };
        },
        //是否已经结束
        isEnded: function() {
            var now = parseInt(moment().format('X'));
            var ended = false;
            if(this.get('endAt') <= now) ended = true;
            return ended;
        },
        //是否已经开始
        isStarted: function() {
            var now = parseInt(moment().format('X'));
            var started = false;
            if(this.get('startAt') <= now) started = true;
            return started;
        },
        //判断相等
        equal: function(model) {
            if(!_.isObject(model)) return false;
            model.startAt = parseInt(model.startAt) || 0;
            model.endAt = parseInt(model.endAt) || 0;
            if(this.get('startAt')==model.startAt && this.get('endAt')==model.endAt) return true;
            return false;
        },
        //判断是否包含
        include: function(model) {
            if(!_.isObject(model)) return false;
            model.startAt = parseInt(model.startAt) || 0;
            model.endAt = parseInt(model.endAt) || 0;
            if(model.endAt>model.startAt && model.startAt>=this.get('startAt') && model.endAt<=this.get('endAt')) return true;
            return false;
        },
        //求交集
        intersection: function(model) {
            if(!_.isObject(model)) return false;
            model.startAt = parseInt(model.startAt) || 0;
            model.endAt = parseInt(model.endAt) || 0;
            if(model.startAt >= model.endAt) return false;
            var _startAt = Math.max(model.startAt, this.get('startAt')),
                _endAt = Math.min(model.endAt, this.get('endAt'));
            if(_startAt >= _endAt) return false; //没有交集
            return {
                startAt: _startAt,
                endAt: _endAt
            };
        }
    });
});